import 'package:sinosheets/utils/favorite/product_service.dart';
import 'package:sinosheets/utils/favorite/flash_sale_product_model.dart';
import 'package:sinosheets/utils/favorite/normal_product_model.dart';
import 'package:sinosheets/utils/toast_util.dart';

class ProductUtil {
  static final ProductService _service = ProductService();
  static bool _isInitialized = false;

  /// 初始化商品服务
  static Future<void> init() async {
    if (_isInitialized) return;
    try {
      await _service.init();
      _isInitialized = true;
    } catch (e) {
      print('ProductUtil初始化失败: $e');
      rethrow;
    }
  }

  static bool get isInitialized => _isInitialized;
  static ProductService get service => _service;

  // ==================== FlashSaleProduct 收藏 ====================
  static Future<bool> toggleFlashSaleProductFavorite(Map<String, dynamic> productData) async {
    if (!_isInitialized) {
      ToastUtil.showText('服务未初始化');
      return false;
    }
    final result = await _service.toggleFlashSaleProductFavorite(productData);
    if (result) {
      ToastUtil.showText('Added to favorites');
    } else {
      ToastUtil.showText('Removed from favorites');
    }
    return result;
  }

  static Future<bool> isFlashSaleProductFavorite(String productId) async {
    if (!_isInitialized) return false;
    return await _service.isFlashSaleProductFavorite(productId);
  }

  // ==================== NormalProduct 收藏 ====================
  static Future<bool> toggleNormalProductFavorite(Map<String, dynamic> productData) async {
    if (!_isInitialized) {
      ToastUtil.showText('服务未初始化');
      return false;
    }
    final result = await _service.toggleNormalProductFavorite(productData);
    if (result) {
      ToastUtil.showText('Added to favorites');
    } else {
      ToastUtil.showText('Removed from favorites');
    }
    return result;
  }

  static Future<bool> isNormalProductFavorite(String productId) async {
    if (!_isInitialized) return false;
    return await _service.isNormalProductFavorite(productId);
  }

  // ==================== 通用操作 ====================
  static List<FlashSaleProductModel> get favoriteFlashSaleProducts {
    if (!_isInitialized) return [];
    return _service.favoriteFlashSaleProducts;
  }

  static List<NormalProductModel> get favoriteNormalProducts {
    if (!_isInitialized) return [];
    return _service.favoriteNormalProducts;
  }

  static Future<void> refreshAllData() async {
    if (!_isInitialized) return;
    await _service.refreshAllData();
  }

  static Future<void> clearAllFavorites() async {
    if (!_isInitialized) return;
    await _service.clearAllFavorites();
  }

  static Map<String, dynamic> exportProductData() {
    if (!_isInitialized) return {};
    return _service.exportProductData();
  }

  static Future<void> close() async {
    if (_isInitialized) {
      await _service.close();
      _isInitialized = false;
    }
  }
}
